package com.tinem.platform.web.auth.server.client;

import com.tinem.platform.module.pojo.co.RedisKeyEnum;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.oauth2.common.util.SerializationUtils;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;

/**
 * @author fengzhihao
 * @version v1
 * @program: platform
 * @className RedisAuthorizationCodeServices
 * @description TODO
 * @site 
 * @company 
 * @create 2020-07-02 14:38
 */
@Service
@Slf4j
public class RedisAuthorizationCodeServices extends RandomValueAuthorizationCodeServices {
    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Value("${auth.code.effectiveTime}")
    Duration authCodeEffectiveTime;
    @Override
    protected void store(String code, OAuth2Authentication authentication) {
        log.info("generate code:({})",code);
        String value = Base64.encode(SerializationUtils.serialize(authentication));
        stringRedisTemplate.opsForValue().set(RedisKeyEnum.auth_code.getKey(code),value, authCodeEffectiveTime);
    }

    @Override
    protected OAuth2Authentication remove(String code) {
        String value = stringRedisTemplate.opsForValue().getAndSet(RedisKeyEnum.auth_code.getKey(code),"");
        stringRedisTemplate.delete(RedisKeyEnum.auth_code.getKey(code));
        if(value == null){
            log.warn("code({}) is null",code);
        }
        if(StrUtil.isBlank(value)){
            log.warn("code({}) repeat",code);
            return null;
        }
        log.info("code({}) remove success",code);
        return SerializationUtils.deserialize(Base64.decode(value));
    }
}
